package pl.edu.agh.jemo.evolution.selections.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import pl.edu.agh.jemo.evolution.objfunc.ObjectiveFunctionSet;
import pl.edu.agh.jemo.evolution.objfunc.impl.clustering.Clusterizer;
import pl.edu.agh.jemo.evolution.population.Population;
import pl.edu.agh.jemo.gui.chart.Plot;
import pl.edu.agh.jemo.gui.chart.Plotter;


public class ClusteredNSGA2CrowdingSelection extends NSGA2CrowdingSelection {
	
	
	private Clusterizer clusterizer = new Clusterizer();
	
	public void performClusteredTournament(Population population, ObjectiveFunctionSet objectiveFunctionSet) {
		clusterizer.setPopulationReference(population);
		ArrayList<Population> clusters = clusterizer.getClusters();
		
		List<Population> mergedFronts = new ArrayList<Population>();

		for (Population cluster : clusters) {
			cluster.setObjectiveFunctionSet((ObjectiveFunctionSet) objectiveFunctionSet.clone());
			cluster.getObjectiveFunctionSet().setPopulationReference(cluster);
			cluster.calculatePhenotype();
			List<Population> tempFront = fastNondominatedSort(cluster);
			for (int i = 0 ; i < tempFront.size() ; i++) {
				if (i == mergedFronts.size()) {
					mergedFronts.add(new Population());
				}
				mergedFronts.get(i).addAll(tempFront.get(i));
				mergedFronts.get(i).setObjectiveFunctionSet(objectiveFunctionSet);
			}
		}
		
		try {
			Plotter plotter = Plotter.getPlotter();
			Plot plot = new Plot();
			plot.setName("NSGA2FrontsMERGED");
			plot.addPopulation(mergedFronts);
			plotter.addPlot(plot);		
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		prepareNextGeneration(population, mergedFronts);
		
	}

	public Clusterizer getClusterizer() {
		return clusterizer;
	}
	
	

}
